using System;
using HestiaBackup.Library.ConfigurationManager;
using HestiaBackup.Library.Connectors;
using HestiaBackup.Library.Events;

namespace HestiaBackup.Library.Workers
{
    public static class FtpChildWorker
    {
        public static bool Process(int projectId, Settings settings)
        {
            bool finishedWithoutError = true;
            FtpSetting setting = null;
            for (int i = 0; i < settings.FtpSettings.Count; i++)
            {
                if (settings.FtpSettings[i].ID == projectId)
                {
                    setting = settings.FtpSettings[i];
                }
            }
            if (setting == null)
            {
                RaiseError("The project id isn't part of projects", null);
                throw new IndexOutOfRangeException("The project id isn't part of projects");
            }

            FtpConnector connector = new FtpConnector(setting);

            connector.OnFileDownloaded += new EventHandler<FileDownloadedEventArgs>(connector_OnFileDownloaded);
            connector.OnFileAlreadyUpToDate += new EventHandler<FileDownloadedEventArgs>(connector_OnFileAlreadyUpToDate);
            connector.Process();

            return finishedWithoutError;
        }

        private static void connector_OnFileAlreadyUpToDate(object sender, FileDownloadedEventArgs e)
        {
            if (OnFileAlreadyUpToDate != null)
            {
                OnFileAlreadyUpToDate(sender, e);
            }
        }

        private static void connector_OnFileDownloaded(object sender, FileDownloadedEventArgs e)
        {
            if (OnFileDownloaded != null)
            {
                OnFileDownloaded(sender, e);
            }
        }

        public static void RaiseError(string message, FtpSetting setting)
        {
            if (OnTransferError != null)
            {
                ChildWorkerErrorEventArgs args = new ChildWorkerErrorEventArgs();
                args.Message = message;
                OnTransferError(setting, args);
            }
        }

        public static event EventHandler<FileDownloadedEventArgs> OnFileDownloaded;
        public static event EventHandler<FileDownloadedEventArgs> OnFileAlreadyUpToDate;
        public static event EventHandler<ChildWorkerErrorEventArgs> OnTransferError;
    }
}